import React, { useState, useEffect } from 'react';
import { Button, Modal, Form, Input, Row, Col } from 'antd';
import TRNotification from '#/utils/notification.js';
import { HttpCode } from '#/utils/contacts.js';
import planIcon from '@/assets/img/plan_icon.png';
import type { IApplyType, IStationsData, IDataSourceType, IDealElementOptions } from '../../type';
import { IOperationType } from '../../type';
import { modalTitleMap, visibleList } from '../../dictionary';
import { postGetStationsByIds } from '../../service';
import { ShowSelect } from '../index';
import styles from './index.less';

interface IProps {
  /**
   * 操作类型
   */
  operationType: IOperationType;

  /**
   * 交易单元
   */
  stationData: IStationsData;
  /**
   * 省份数据
   */
  provinceOptions: IDealElementOptions[];
  /**
   * 集团数据
   */
  groupOptions: IDealElementOptions[];
  /**
   * 数据
   */
  data: IDataSourceType;

  onPress: (data: Record<string, any>) => void;
  onOk: (params: IApplyType) => void;
}

const ApplyModalComponent = (props: IProps) => {
  const {
    onOk,
    onPress,
    operationType = IOperationType.ADD,
    data,
    stationData,
    provinceOptions,
    groupOptions,
  } = props;
  const [form] = Form.useForm();
  const [visible, setVisible] = useState<boolean>(true);
  const [loading, setLoading] = useState<boolean>(false);
  const [provinceId, setProvinceId] = useState<string>();
  const [groupId, setGroupId] = useState<string>();
  const { dealElementOptions = [], dealElementDataObj } = stationData;

  useEffect(() => {
    const _data: IApplyType = {
      stationId: data?.stationId ? String(data?.stationId) : undefined,
      showName: data?.showName ? data?.showName : undefined,
      latitude:
        data?.latitude || data?.latitude === 0 ? Number(data?.latitude).toFixed(6) : undefined,
      longitude:
        data?.longitude || data?.longitude === 0 ? Number(data?.longitude).toFixed(6) : undefined,
      visible: operationType === IOperationType.ADD ? 1 : data?.visible ? 1 : 0,
    };
    setGroupId(data?.groupId ? String(data?.groupId) : undefined);
    setProvinceId(data?.provinceId ? String(data?.provinceId) : undefined);
    form && form.setFieldsValue(_data);
  }, [data]);

  // 改变交易单元
  const onChangeStation = async (e: any) => {
    const value = form && form.getFieldsValue();
    const _provinceId = value?.stationId
      ? dealElementDataObj[value.stationId][0]?.provinceId
      : undefined;
    const _groupId = groupOptions.find((item) => {
      return item.children?.find((m) => {
        return m.value === e;
      });
    })?.value;
    const res = await postGetStationsByIds({ stationIds: [e] });
    if (res && res.statusCode === HttpCode.SUCCESS) {
      const _longitude = res?.stationList[0]
        ? Number(res?.stationList[0]?.longitude).toFixed(6)
        : undefined;
      const _latitude = res?.stationList[0]
        ? Number(res?.stationList[0]?.latitude).toFixed(6)
        : undefined;
      form &&
        form.setFieldsValue({
          ...value,
          longitude: _longitude,
          latitude: _latitude,
          provinceId: _provinceId,
          groupId: _groupId,
          showName: dealElementOptions.find((item) => item.value === value?.stationId)?.label,
        });
    } else {
      form &&
        form.setFieldsValue({
          ...value,
          longitude: '',
          latitude: '',
          provinceId: _provinceId,
          groupId: _groupId,
          showName: dealElementOptions.find((item) => item.value === value?.stationId)?.label,
        });
    }
    setGroupId(_groupId);
    setProvinceId(_provinceId);
  };

  const onBlur = (e: any, key: string) => {
    const value = form && form.getFieldsValue();
    let _value = e?.target?.value;
    const keyList1 = ['longitude', 'latitude'];
    if (keyList1.includes(key)) {
      _value = Number(_value) >= 0 ? _value : 0;
      _value = (parseInt(String(_value * 1000000)) / 1000000).toFixed(6);
    }
    form &&
      form.setFieldsValue({
        ...value,
        [key]: _value,
      });
  };

  // 取消
  const _onCancel = () => {
    setVisible(false);
    onPress({ index: 0 });
  };

  // 确认
  const _onOk = async () => {
    form &&
      form.validateFields().then(async (value) => {
        setLoading(true);
        const _value: IApplyType = {
          ...value,
          latitude: value?.latitude ? Number(value?.latitude) : undefined,
          longitude: value?.longitude ? Number(value?.longitude) : undefined,
          stationId: value?.stationId,
          stationName: dealElementOptions.find((item) => item.value === value?.stationId)?.label,
          groupId: groupId,
          groupName: groupOptions.find((item) => item.value === groupId)?.label,
          provinceId: provinceId,
          provinceName: provinceOptions.find((item) => item.value === provinceId)?.label,
          visible: !!value?.visible,
          id: data?.id,
        };
        const res: any = await onOk(_value);
        if (res && res.statusCode === HttpCode.SUCCESS) {
          setVisible(false);
          onPress({ index: 1, statusCode: HttpCode.SUCCESS });
        }
        setLoading(false);
      });
  };

  const filterOption = (input: string, option: { value: any; label: any }) => {
    const { value, label } = option;
    return (
      value?.toLowerCase().indexOf(input.toLowerCase()) >= 0 ||
      label?.toLowerCase().indexOf(input.toLowerCase()) >= 0
    );
  };

  const footerRender = () => {
    return [
      <Button key="dtest1" onClick={_onCancel} loading={loading}>
        取消
      </Button>,
      <Button key="dtest2" type="primary" onClick={_onOk} loading={loading}>
        确定
      </Button>,
    ];
  };

  return (
    <Modal
      className={styles.modal}
      centered
      width={792}
      maskClosable={false}
      visible={visible}
      title={
        <div className={styles.titleDiv}>
          <img src={planIcon} className={styles.titleLogo} />
          <span className={styles.title}>{modalTitleMap[operationType]}</span>
        </div>
      }
      onCancel={_onCancel}
      footer={footerRender()}
    >
      <div className={styles.container}>
        <Form
          className={styles.form}
          form={form}
          name="apply"
          labelCol={{ span: 8 }}
          wrapperCol={{ span: 16 }}
          colon={false}
          labelAlign="left"
          autoComplete="off"
          requiredMark={false}
        >
          <Row className={styles.row}>
            <Col span={11}>
              <Form.Item
                name="stationId"
                label="交易单元"
                rules={[{ required: true, message: '请选择交易单元' }]}
              >
                <ShowSelect
                  placeholder={'交易单元'}
                  showArrow={true}
                  options={dealElementOptions}
                  showSearch={true}
                  filterOption={filterOption as any}
                  disabled={operationType === IOperationType.EDIT}
                  onChange={onChangeStation}
                />
              </Form.Item>
            </Col>
            <Col span={11} offset={2}>
              <Form.Item
                name="showName"
                label="显示名称"
                rules={[
                  { required: true, message: '请填写显示名称' },
                  {
                    pattern: /^[\u4E00-\u9FA5A-Za-z0-9]{0,10}$/,
                    message: '显示名称仅允许输入中英文及数字',
                  },
                ]}
              >
                <Input maxLength={10} placeholder="显示名称" />
              </Form.Item>
            </Col>
          </Row>
          <Row className={styles.row}>
            <Col span={11}>
              <Form.Item
                name="longitude"
                label="东经"
                rules={[
                  { required: true, message: '请填写东经' },
                  { pattern: /^[0-9]*(\.[0-9]*)?$/, message: '请输入小数' },
                ]}
              >
                <Input placeholder="东经" onBlur={(e) => onBlur(e, 'longitude')} />
              </Form.Item>
            </Col>
            <Col span={11} offset={2}>
              <Form.Item
                name="latitude"
                label="北纬"
                rules={[
                  { required: true, message: '请填写北纬' },
                  { pattern: /^[0-9]*(\.[0-9]*)?$/, message: '请输入小数' },
                ]}
              >
                <Input placeholder="北纬" onBlur={(e) => onBlur(e, 'latitude')} />
              </Form.Item>
            </Col>
          </Row>
          <Row className={styles.row}>
            <Col span={11}>
              <Form.Item name="visible" label="是否显示">
                <ShowSelect placeholder={'是否显示'} showArrow={false} options={visibleList} />
              </Form.Item>
            </Col>
          </Row>
        </Form>
      </div>
    </Modal>
  );
};

class ApplyModal {
  __key__ = '';

  show = (props: any) => {
    return new Promise((resolve) => {
      if (this.__key__ !== '') return;
      this.__key__ = String(Date.now());
      TRNotification.add({
        key: this.__key__,
        content: (
          <ApplyModalComponent
            {...props}
            onPress={(result: any) => {
              TRNotification.remove(this.__key__);
              this.__key__ = '';
              resolve(result);
            }}
          />
        ),
        duration: null,
        dismiss: this.dismiss,
      });
    });
  };

  dismiss = () => {
    if (this.__key__.length > 0) {
      TRNotification.remove(this.__key__);
      this.__key__ = '';
    }
  };
}

export default new ApplyModal();
